package com.hentica.app.component.photo;

import android.app.Activity;
import android.content.ContentValues;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.provider.MediaStore;
import android.support.v4.app.Fragment;
import android.util.Log;

import com.hentica.imagecompress.CompressListener;
import com.hentica.imagecompress.CompressUtil;
import com.hentica.imagecompress.Option;
import com.soundcloud.android.crop.Crop;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by pxy on 2018/2/25.
 */

public class TakePhotoAlbum implements TakePhoto {
    private List<String> photos;
    private TakePhotoCallBack takePhotoCallBack;
    private Activity activity;
    private CropOption option = new CropOption();
    private Option mComprossOption = new Option();
    private boolean isCrop;
    private boolean isCompross;
    private Fragment fragment;
    private static final String ASPECT_X = "aspect_x";
    private static final String ASPECT_Y = "aspect_y";
    private static final String MAX_X = "max_x";
    private static final String MAX_Y = "max_y";
    private final int CODE_PICK_ALBUM = 2;
    private static final int IMAGE_CROP_CODE = 9;
    private File cropImageFile;

    public TakePhotoAlbum(Activity activity, boolean isCrop, TakePhotoCallBack takePhotoCallBack) {
        this.activity = activity;
        this.isCrop = isCrop;
        this.takePhotoCallBack = takePhotoCallBack;
        this.photos = new ArrayList();
    }

    public TakePhotoAlbum(Activity activity, boolean isCrop, CropOption option, boolean isCompross, Option mComprossOption, TakePhotoCallBack takePhotoCallBack) {
        this.activity = activity;
        this.isCrop = isCrop;
        this.takePhotoCallBack = takePhotoCallBack;
        this.option = option;
        this.mComprossOption = mComprossOption;
        this.isCompross = isCompross;
        this.photos = new ArrayList();
    }

    public TakePhotoAlbum(Fragment fragment, Activity activity, boolean isCrop, CropOption option, boolean isCompross, Option mComprossOption, TakePhotoCallBack takePhotoCallBack) {
        this.activity = activity;
        this.isCrop = isCrop;
        this.takePhotoCallBack = takePhotoCallBack;
        this.option = option;
        this.fragment = fragment;
        this.mComprossOption = mComprossOption;
        this.isCompross = isCompross;
        this.photos = new ArrayList();
    }

    private Uri beforeCurrentUri;

    public void handleActivityResult(int requestCode, int resultCode, Intent data) {
        Log.d("dwqdwqdwq", "handleActivityResult");
        if (resultCode == Activity.RESULT_OK && requestCode == IMAGE_CROP_CODE) {
            if (this.cropImageFile != null) {
                this.complete(this.cropImageFile.getAbsolutePath());
            } else {
                this.error();
            }
        } else if (resultCode == Activity.RESULT_OK && requestCode == CODE_PICK_ALBUM && data != null) {
            beforeCurrentUri = data.getData();
            if (isCrop) {
                crop(this.selectPhoto(data.getData()));
            } else {
                complete(this.selectPhoto(data.getData()));
            }
        } else if(beforeCurrentUri != null){
            complete(selectPhoto(beforeCurrentUri));
        }

    }

    public void takePhoto() {
        Intent albumIntent = new Intent("android.intent.action.PICK", MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
        if (this.fragment != null) {
            this.fragment.startActivityForResult(albumIntent, 2);
        } else {
            this.activity.startActivityForResult(albumIntent, 2);
        }

    }

    public void detch() {
        this.activity = null;
    }

    private void crop(String imagePath) {
        if (this.activity != null) {
            this.cropImageFile = new File(FileUtils.createRootPath(this.activity) + "/" + System.currentTimeMillis() + ".jpg");
            Uri destination = Uri.fromFile(this.cropImageFile);
            Uri source = Uri.fromFile(new File(imagePath));
            Crop.of(source, destination).withMaxSize(this.option.maxSizeX, this.option.maxSizeY).withAspect(this.option.aspectX, this.option.aspectY).start(this.activity, this.fragment);
        }

    }

    private Uri getImageContentUri(File imageFile) {
        if (this.activity != null) {
            String filePath = imageFile.getAbsolutePath();
            Cursor cursor = this.activity.getContentResolver().query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, new String[]{"_id"}, "_data=? ", new String[]{filePath}, (String)null);
            if (cursor != null && cursor.moveToFirst()) {
                int id = cursor.getInt(cursor.getColumnIndex("_id"));
                Uri baseUri = Uri.parse("content://media/external/images/media");
                cursor.close();
                return Uri.withAppendedPath(baseUri, "" + id);
            } else if (imageFile.exists()) {
                ContentValues values = new ContentValues();
                values.put("_data", filePath);
                if (cursor != null) {
                    cursor.close();
                }

                return this.activity.getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
            } else {
                return null;
            }
        } else {
            return null;
        }
    }

    private String selectPhoto(Uri uri) {
        String[] filePathColum = new String[]{"_data"};
        Cursor cursor = this.activity.getContentResolver().query(uri, filePathColum, (String)null, (String[])null, (String)null);
        cursor.moveToFirst();
        int columIndex = cursor.getColumnIndex(filePathColum[0]);
        String path = cursor.getString(columIndex);
        cursor.close();
        return path;
    }

    private void complete(String path) {
        this.photos.clear();
        this.photos.add(path);
        if (this.takePhotoCallBack != null) {
            if (this.isCompross) {
                CompressUtil.compressBitmaps(this.photos, this.mComprossOption, new CompressListener() {
                    public void result(List<String> filePaths) {
                        TakePhotoAlbum.this.takePhotoCallBack.getPhotos(filePaths);
                    }
                });
            } else if (this.takePhotoCallBack != null) {
                this.takePhotoCallBack.getPhotos(this.photos);
            }
        }

    }

    private void error() {
        if (this.takePhotoCallBack != null) {
            this.takePhotoCallBack.error();
        }

    }
}
